package net.jsoft.pms.web.mysql.problem;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import net.jsoft.platform.core.util.platform.PlatformUtils;
import net.jsoft.platform.core.web.BaseController;
import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;
import net.jsoft.pms.entity.problem.ProblemTask;
import net.jsoft.pms.service.mysql.problem.IProblemService;
import net.sf.json.JSONArray;

/**
 * 问题管理平台控制器
 *
 * @author John
 * @Date 2017-08-03 10:55:31
 */
@Controller
@RequestMapping("/problem")
public class ProblemController extends BaseController
{

    private String PREFIX = "/pms/mysql/problem/";

    @Resource(name = "problemServiceImpl")
    IProblemService service;

    @Resource(name = "mysqlJdbcTemplate")
    private JdbcTemplate template;

    @Autowired
    private UserRepository userRepository;

    private NumberFormat numberFormat = NumberFormat.getInstance();

    /**
     * 跳转到问题管理平台首页
     */
    @RequestMapping("/overall")
    public String overall()
    {
        return PREFIX + "overall";
    }

    /**
     * 
     * @return
     * @throws ParseException 
     */
    @RequestMapping("/overallData")
    @ResponseBody
    public Map<String, Object> overallData(String date) throws ParseException
    {

        Map<String, Object> resp = new HashMap<String, Object>();
        List<ProblemTask> all = null;
        //本周问题
        List<ProblemTask> thisWeek = null;

        //剩余剩余
        List<ProblemTask> left = null;
        Date d = null;
        if (StringUtils.isEmpty(date))
        {
            d = PlatformUtils.getdate((PlatformUtils.getdate(new Date())).substring(0, 10));
        }
        else
        {
            d = PlatformUtils.getdate(date);
        }

        Map<String, Date> map = PlatformUtils.getDays(d);

        all = service.findAll();
        left = service.findProblemTaskByStatus("1");
        //
        thisWeek = service.findProblemTaskByPeriod(map.get("thisWeekMonday"), map.get("thisWeekSunday"));
        Map<String, List<ProblemTask>> temp = service.dealedProblemTask(thisWeek, map.get("lastWeekSunday"));
        List<ProblemTask> thisWeekNew = temp.get("new");
        List<ProblemTask> thisWeekDealed = temp.get("dealed");
        List<ProblemTask> thisWeekLeft = temp.get("left");

        Map<String, List<ProblemTask>> thisWeekGroup = service.group(thisWeek);
        Map<String, List<ProblemTask>> thisWeekDealGroup = service.group(thisWeekDealed);
        Map<String, List<ProblemTask>> thisWeekNewGroup = service.group(thisWeekNew);
        Map<String, List<ProblemTask>> thisWeekLeftGroup = service.group(thisWeekLeft);
        StringBuffer info = new StringBuffer();
        info.append("问题管理平台统计：<br/>");
        numberFormat.setMaximumFractionDigits(2);
        info.append("合计问题数：共").append(all.size()).append("个，处理").append(all.size() - left.size()).append("个，剩余").append(left.size()).append("个，完成率为：")
                .append(numberFormat.format((float) (all.size() - left.size()) / (float) all.size() * 100)).append("%<br/>");
        info.append("本周问题数：<a href='javascript:openProblem()' >共").append(thisWeek.size()).append("个</a>，处理").append(thisWeekDealed.size()).append("个,新增").append(thisWeekNew.size()).append("个，剩余")
                .append(thisWeekLeft.size()).append("个，完成率为：").append(numberFormat.format((float) thisWeekDealed.size() / (float) thisWeek.size() * 100)).append("%<br/>");
        for (String k : thisWeekGroup.keySet())
        {
            int totalNum = thisWeekGroup.get(k) == null ? 0 : thisWeekGroup.get(k).size();
            int dealNum = thisWeekDealGroup.get(k) == null ? 0 : thisWeekDealGroup.get(k).size();
            int addNum = thisWeekNewGroup.get(k) == null ? 0 : thisWeekNewGroup.get(k).size();
            int leftNum = thisWeekLeftGroup.get(k) == null ? 0 : thisWeekLeftGroup.get(k).size();
            info.append(k).append("问题数：共").append(totalNum).append("个，处理").append(dealNum).append("个，新增").append(addNum).append("个，剩余").append(leftNum).append("个,完成率为：")
                    .append(numberFormat.format((float) dealNum / (float) totalNum * 100)).append("%<br/>");
        }

        info.append("<script>");
        info.append("function openProblem(){");
        info.append("var tempPro = ").append(JSONArray.fromObject(thisWeek).toString()).append(";");
        info.append("var title ='本周问题';");
        info.append("layer.open({");
        info.append("type : 2,");
        info.append("title : title,");
        info.append("shadeClose : true,");
        info.append("shade : false,");
        info.append("maxmin : true,");
        info.append("area : [ '893px', '500px' ],");
        info.append("content : '/problem/problemsPage',");
        info.append("success : function(layero, index) {");
        info.append("var iframeWin = window[layero.find('iframe')[0]['name']];");
        info.append("var flag = iframeWin.setTable(tempPro);");
        info.append("}");
        info.append("});");
        info.append("}");

        info.append("</script>");

        resp.put("info", info.toString());

        return resp;
    }

    /**
     * 跳转到问题管理平台首页
     */
    @RequestMapping("/uploadFilePage")
    public String uploadFile()
    {
        return PREFIX + "uploadFilePage";
    }

    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public void importFile(HttpServletRequest req, @RequestParam(value = "problemFile") MultipartFile file) throws Exception
    {
        //判断文件是否为空
        if (file == null)
        {
            throw new Exception("文件为空");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();

        //验证文件名是否合格
        if (!PlatformUtils.validateExcel(fileName))
        {
            throw new Exception("文件必须是excel格式！");
        }

        //进一步判断文件内容是否为空（即判断其大小是否为0或其名称是否为null）
        long size = file.getSize();
        if (StringUtils.isEmpty(fileName) || size == 0)
        {
            throw new Exception("文件不能为空！");
        }

        //批量导入
        service.batchImport(file.getInputStream());

    }

    @RequestMapping("/problemsPage")
    public String problemsPage()
    {
        return PREFIX + "problemsPage";
    }

    @RequestMapping("/queryProblemUndone")
    public String queryProblemUndone(Model model)
    {
        List<ProblemTask> list = service.findProblemTaskByStatus("1");
        //            JsonConfig config = new JsonConfig();
        //            config.setExcludes(new String[]
        //            { "user" });//除去emps属性
        model.addAttribute("list", JSONArray.fromObject(list).toString());
        return PREFIX + "queryProblemUndone";
    }

    /**
     * 跳转到计划管理首页
     */
    @RequestMapping("/list")
    public String list()
    {
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject listData(int pageSize, int pageNumber, final String sszb, final String beginDate, final String endDate, final String optUser, final String zt, final String earlyDate,
            final String plan) throws ParseException
    {
        //组别 , 人员，录入时间起 , 录入时间止，是否完成，是否安排计划，是否确定计划时间。 
        String sql = "select * from( select GROUP_CONCAT(t.id SEPARATOR ',') taskId, p.id,content,dealDate,insertDate,level,status,title,p.dept,p.optPerson,startDate,endDate from t_dzswj_problem p left join  t_dzswj_plan t on p.id = t.problemId";
        String where = " where 1= 1 ";

        String whereWW = "";

        if (StringUtils.isNotEmpty(sszb))
        {
            where += " and p.dept = " + sszb;
        }
        if (StringUtils.isNotEmpty(optUser))
        {
            where += " and p.optPerson = " + sszb;
        }
        if (StringUtils.isNotEmpty(zt))
        {
            where += " and status = " + zt;
        }
        if (StringUtils.isNotEmpty(earlyDate))
        {
            if ("0".endsWith(earlyDate))
            {
                where += " and (startDate is null or  endDate is null) ";
            }
            else
            {
                where += " and  (startDate is not null  and  endDate is not  null) ";
            }

        }

        if (StringUtils.isNotEmpty(beginDate) || StringUtils.isNotEmpty(endDate))
        {
            if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate))
            {
                where = " and insertDate between '" + beginDate + "'and '" + endDate + "'";
            }
            else
            {
                if (StringUtils.isNotEmpty(beginDate))
                {
                    where += " and  insertDate >= '" + beginDate + "' ";
                }
                if (StringUtils.isNotEmpty(endDate))
                {
                    where += " and  insertDate <= '" + endDate + "' ";
                }
            }

        }

        if (StringUtils.isNotEmpty(plan))
        {
            if ("0".endsWith(plan))
            {
                whereWW += " and taskId is null ";
            }
            else
            {
                whereWW += " and taskId is not null ";
            }

        }

        String groupby = " group by p.id,content,dealDate,insertDate,level,status,title,p.dept,p.optPerson,startDate,endDate ) ww where 1=1 ";
        String limited = " limit ?,? ";
        List<Map<String, Object>> list = null;

        List<ProblemTask> pts = new ArrayList<ProblemTask>();
        ProblemTask pt = null;
        int result = 0;
        try
        {
            String countSql = "select count(1) from (" + sql + where + groupby + whereWW + ") cc";
            System.out.println(countSql);
            result = template.queryForObject(countSql, Integer.class);

            list = template.queryForList(sql + where + groupby + whereWW + limited, new Object[]
            { (pageNumber - 1) * pageSize, pageSize });

            for (Map<String, Object> map : list)
            {
                pt = new ProblemTask();
                //  ,,p.dept,p.optPerson,,endDate 
                pt.setContent(map.get("content") + "");
                pt.setId(map.get("id") + "");
                pt.setDealDate((Date) map.get("dealDate"));
                pt.setInsertDate((Date) map.get("insertDate"));
                pt.setLevel(map.get("level") + "");
                pt.setStatus(map.get("status") + "");
                pt.setTitle(map.get("title") + "");
                SysUser user = userRepository.findOne((Long) map.get("optPerson"));
                pt.setOptPerson(user);
                pt.setDept(user.getDept());
                pt.setStartDate((Date) map.get("startDate"));
                pt.setEndDate((Date) map.get("endDate"));
                String s = "";
                byte[] taskIdBlob = (byte[]) map.get("taskId");
                if (taskIdBlob != null)
                {
                    s = new String(taskIdBlob);
                }

                pt.setTaskId(s + "");
                pts.add(pt);
            }
        }
        catch (DataAccessException e)
        {
            e.printStackTrace();
        }
        JSONObject json = new JSONObject();
        json.put("rows", pts); //这里的 rows 和total 的key 是固定的 
        json.put("total", result);
        return json;
    }
}
